﻿using Stee.CAP8.MessageBus.Interface.Models;
using Stee.CAP8.MessageBus.Sagas.Core;
using Stee.CAP8.MessageBus.Sagas.Core.Sagas;
using Stee.CAP8.MessageBus.Sagas.Order.Sagas;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Stee.CAP8.MessageBus.Sagas.Order.Sagas.Data;

namespace Stee.CAP8.MessageBus.Sagas.Order
{
    public class HandleMessages : IHandleMessage<CommandMessage>
    {
        public IServiceProvider _serviceProvider;
        public ISagaStorage _sagaStorage;

        private List<string> OrderActions = new List<string> { "PaymentSub.Payment", "StockSub.StockAdjust" };
        public HandleMessages(IServiceProvider serviceProvider, ISagaStorage sagaStorage)
        {
            _serviceProvider = serviceProvider;
            _sagaStorage = sagaStorage;
        }
        //这里写当你收到了自己订阅的消息以后怎么办，
        //调用哪个saga类的哪个方法
        public async Task Handle(CommandMessage message)
        {
            var sagaId = message.CorrelationID;
          
            var actionName = message.Action;
            //处理OrderSagaMain
            if (OrderActions.Contains(actionName))
            {
                //从存储中取saga状态
                var (prefMessage, sagaData) = await _sagaStorage.Find<OrderSagaData>(sagaId);
                //调用saga处理sagaData
                var  sagaHandler = _serviceProvider.GetService<OrderSagaMain>();
                await sagaHandler.HandleReply(message,sagaData);
                //将sagaData存储到storage中
                await _sagaStorage.Update<OrderSagaData>(message, sagaData);
            }
             
        }


    }


}
